﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

public partial class Stock : EditBasePage
{
    public Stock()
    {

    }
    protected override void OnLoad(EventArgs e)
    {
        HttpContext.Current.Session["LastUrl"] = "./Stock.aspx";
        this.ViewStateConst = "StockService";
        this.listViewHolder = this.ListView;
        this.objectServiceHolder = objService;
        this.targetMailAddress = MailAccounts.GetInstance().Stock;
        this.confirmButtonHolder = this.Button4;
        base.OnLoad(e);
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        this.Label2.Text = null;
        Utility.CheckLoginAndRedirect();

        global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
        if (user.Money - user.ConsumedMoneyEveryMonth < StockService.ItemPrice)
        {
            this.Label2.ForeColor = Color.Red;
            this.Label2.Text = ConstStrings.NotEnoughMoney;
            return;
        }
        StockService service = ViewState[ViewStateConst] as StockService;
        if (service == null)
        {
            service = new StockService();
            ViewState[ViewStateConst] = service;
        }

        // Validate input:
        string stockKey = this.StockIDTextbox.Text.Trim();
        List<StockServiceEntity> results = this.GetStocksByKey(stockKey);

        if (results.Count == 0)
        {
            this.Label2.ForeColor = Color.Red;
            this.Label2.Text = ConstStrings.NoStock;
            return;
        }

        if (results.Count > 1)
        {
            string err = ConstStrings.MultiStock;
            foreach (StockServiceEntity entity in results)
            {
                err += entity.StockId;
                err += " ";
            }
            this.Label2.ForeColor = Color.Red;
            this.Label2.Text = err;
            return;
        }

        results[0].HighPrice = this.Textbox1.Text.Trim();
        results[0].LowPrice = this.Textbox2.Text.Trim();
        service.Entities.Add(results[0]);
        this.ListView.DataBind();
        foreach (ListViewDataItem item in this.ListView.Items)
        {
            this.ListView.UpdateItem(item.DataItemIndex, false);
        }
    }

    protected void objService_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        // pass in ViewState for accessing from the class
        if (ViewState[ViewStateConst] != null)
        {
            e.ObjectInstance = ViewState[ViewStateConst] as StockService;
        }
        else
        {
            global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
            ServiceManager serviceManager = ServiceManager.LoadFromFile(user.ServiceFileName);
            if (serviceManager != null && serviceManager.StockService != null)
            {
                e.ObjectInstance = serviceManager.StockService;
            }
            else
            {
                e.ObjectInstance = new StockService();
            }
            ViewState[ViewStateConst] = e.ObjectInstance;
        }
    }

    protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
        // These could also be defined in the aspx and just referenced here with like e.NewValues["ListIndex"]..  but if
        //  we have to do them manually for the Delete anyway, might as well do them all manually and keep them together 
        //   in the code-behind.
        this.objService.UpdateParameters.Clear();
        objService.UpdateParameters.Add(new Parameter("ListIndex", TypeCode.Int16, e.ItemIndex.ToString()));
        objService.UpdateParameters.Add(new Parameter("StockId", TypeCode.String,
            ((TextBox)this.ListView.Items[e.ItemIndex].FindControl("IdTextBox")).Text));
        objService.UpdateParameters.Add(new Parameter("StockName", TypeCode.String,
            ((TextBox)this.ListView.Items[e.ItemIndex].FindControl("NameTextBox")).Text));
        objService.UpdateParameters.Add(new Parameter("HighPrice", TypeCode.String,
            ((TextBox)this.ListView.Items[e.ItemIndex].FindControl("HighPriceTextBox")).Text));
        objService.UpdateParameters.Add(new Parameter("LowPrice", TypeCode.String,
            ((TextBox)this.ListView.Items[e.ItemIndex].FindControl("LowPriceTextBox")).Text));
    }

    public List<StockServiceEntity> GetStocksByKey(string key)
    {
        List<StockServiceEntity> results = new List<StockServiceEntity>();
        string url = string.Format(@"http://suggest3.sinajs.cn/suggest/type=11,12,13,14,15&key={0}&name=suggestdata_1261670821296", key);
        string data = HtmlUtility.GetDataByUrl(url);
        if (data == null)
        {
            return null;
        }
        string[] datas = data.Split(new char[] { '\"' });
        data = datas[1];
        datas = data.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
        char[] chars = new char[] { ',' };
        if (datas != null)
        {
            foreach (string value in datas)
            {
                datas = value.Split(chars, StringSplitOptions.RemoveEmptyEntries);
                StockServiceEntity entity = new StockServiceEntity
                {
                    StockId = datas[3],
                    StockName = datas[4]
                };
                results.Add(entity);
            }
        }
        return results;
    }

    protected void Button4_Click(object sender, EventArgs e)
    {
        Utility.CheckLoginAndRedirect();
        global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
        ServiceManager serviceManager = ServiceManager.LoadFromFile(user.ServiceFileName);
        this.ListView1_ItemCommand(null, null);
        int original = 0;
        if (serviceManager.StockService != null)
        {
            original = serviceManager.StockService.Entities.Count * StockService.ItemPrice;
        }
        serviceManager.StockService = ViewState[ViewStateConst] as StockService;
        user.ConsumedMoneyEveryMonth = user.ConsumedMoneyEveryMonth - original + 
                                            serviceManager.StockService.Entities.Count * StockService.ItemPrice;
        DataManager dataMan = new DataManager(user.ServiceFileName, typeof(ServiceManager));
        dataMan.SaveData(serviceManager);

        this.Button4.Enabled = false;
        DoStuff action = new DoStuff(this.SendOut);
        action.BeginInvoke(user.PhoneNumber, serviceManager.StockService.SerializeToString(), null, null);
    }
}